package com.zcoj.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcoj.core.model.ApiResponse;
import com.zcoj.mapper.JudgeMapper;
import com.zcoj.pojo.Dto.Judge;
import com.zcoj.pojo.Vo.homeLineCharVO;
import com.zcoj.service.homePageService;
import com.zcoj.util.RedisCaches;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author chenbin
 * @version 1.0
 * @description: TODO
 * @date 2023/3/30 10:48
 */
@Slf4j
@Service
public class homePageServiceImpl implements homePageService {
 @Autowired
 private JudgeMapper judgeMapper;


 @Autowired
 private RedisCaches redisCaches;

 @Override
 public ApiResponse lineChart() {

  String today = DateUtil.today();
  String lineChartRedisCache="lineChart_"+today;
  Object cacheObject = redisCaches.getCacheObject(lineChartRedisCache);
  if (Objects.isNull(cacheObject)){
   Date currentDate = new Date();
   List<homeLineCharVO> lineCharVOS =new ArrayList<>();
   // 获取最近7天的日期
   for (int i = 0; i < 7; i++) {
    Date nextDate = DateUtil.offsetDay(currentDate, -i+1);
    Date date=DateUtil.offsetDay(currentDate,-i);
    String formattedNextDate = DateUtil.format(nextDate, "yyyy-MM-dd");
    String formattedDate = DateUtil.format(date, "yyyy-MM-dd");
    homeLineCharVO homeLineCharVO = new homeLineCharVO();
    homeLineCharVO.setDate(formattedDate);
    //统计通过次数
    QueryWrapper<Judge> queryWrapper=new QueryWrapper<>();
    queryWrapper.eq("status",0).between("submit_time",formattedDate,formattedNextDate);
    Integer selectPassCount = Math.toIntExact(judgeMapper.selectCount(queryWrapper));
    homeLineCharVO.setPassCount(selectPassCount);
    //统计总数
    queryWrapper.clear();
    queryWrapper.between("submit_time",formattedDate,formattedNextDate);
    Integer selectSubmitCount = Math.toIntExact(judgeMapper.selectCount(queryWrapper));
    homeLineCharVO.setSubmitCount(selectSubmitCount);
    lineCharVOS.add(homeLineCharVO);
   }
   Object json = JSON.toJSON(lineCharVOS);
   redisCaches.setCacheObject(lineChartRedisCache,json,1, TimeUnit.HOURS);
   return ApiResponse.success("", json);
  }else {
   return ApiResponse.success("",cacheObject);
  }


 }
}
